<template>
  <div class="live-container">
    <div class="live-content">
      <!-- 左侧直播播放器 -->
      <div class="live-player-container">
        <div class="live-header">
          <h1>{{ liveDetail.liveTitle }}</h1>
          <p class="live-id">直播ID: {{ liveDetail.liveId }}</p>
        </div>
        <div class="video-wrapper">
          <video class="video-js" ref="videoplayer" width="100%"
                 style="background-color:rgb(18,9,37);width: 100%;height: 100%;">
          </video>
        </div>
      </div>

      <!-- 右侧商品栏 -->
      <div class="products-container">
        <div class="products-header">
          <h2>直播商品</h2>
          <div class="header-actions">
            <p>共 {{ products.length }} 件商品</p>
            <button class="refresh-btn" @click="refreshProducts">
              <i class="refresh-icon"></i> 刷新
            </button>
          </div>
        </div>
        <div class="products-list">
          <div v-for="(product, index) in products" :key="product.id" class="product-item">
            <img :src="getProductImage(product)" :alt="product.name" class="product-image">
            <div class="product-info">
              <h3>{{ product.name }}</h3>
              <p class="product-description">{{ product.description || '暂无描述' }}</p>
              <div class="product-meta">
                <span class="product-price">¥{{ formatPrice(product.price) }}</span>
                <span class="product-stock" :class="{'low-stock': product.stock < 10}">
                  库存: {{ product.stock }}{{ product.unit || '件' }}
                </span>
              </div>
              <div class="product-origin">产地: {{ product.origin || '未知' }}</div>
              <button class="add-to-cart" @click="showBuyDialog(product)">
                <i class="cart-icon"></i> 立即购买
              </button>
            </div>
          </div>
          <div v-if="products.length === 0" class="empty-products">
            <i class="empty-icon"></i>
            <p>暂无商品信息</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 购买弹窗 -->
    <el-dialog
        v-model="buyDialogVisible"
        title="确认订单"
        width="50%"
        @close="handleBuyDialogClose"
    >
      <div class="dialog-product-info">
        <el-image
            :src="currentProduct.imageUrls[0]"
            fit="contain"
            style="width: 120px; height: 120px; margin-right: 20px;"
        />
        <div class="dialog-product-details">
          <h3>{{ currentProduct.name }}</h3>
          <p class="price">¥{{ formatPrice(currentProduct.price) }}</p>
          <p class="stock">库存: {{ currentProduct.stock }}件</p>
        </div>
      </div>

      <el-form :model="orderForm" label-width="100px" class="order-form">
        <el-form-item label="收货地址" required>
          <el-input v-model="orderForm.shippingAddress" placeholder="请输入收货地址" size="large" />
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话" size="large" />
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="orderForm.contactName" placeholder="请输入收货人姓名" size="large" />
        </el-form-item>
        <el-form-item label="支付方式" required>
          <el-select v-model="orderForm.paymentType" placeholder="请选择支付方式" size="large" style="width: 100%">
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="银行卡" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="运费">
          <p class="freight-info">¥{{ formatPrice(orderForm.freight) }}</p>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="orderForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
              size="large"
          />
        </el-form-item>

        <el-form-item label="购买数量">
          <el-input-number
              v-model="orderForm.items[0].quantity"
              :min="1"
              :max="currentProduct.stock"
              controls-position="right"
              size="large"
          />
        </el-form-item>
      </el-form>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总价:</span>
          <span class="value">¥{{ formatPrice(orderForm.items[0].price * orderForm.items[0].quantity) }}</span>
        </div>
        <div class="summary-item">
          <span>运费:</span>
          <span class="value">¥{{ formatPrice(orderForm.freight) }}</span>
        </div>
        <div class="summary-item total">
          <span>应付总额:</span>
          <span class="value">¥{{ formatPrice(orderForm.items[0].price * orderForm.items[0].quantity + orderForm.freight) }}</span>
        </div>
      </div>

      <template #footer>
        <el-button @click="buyDialogVisible = false" size="large">取消</el-button>
        <el-button type="primary" @click="confirmBuy" size="large">提交订单</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import videojs from "video.js";
import {useRoute} from "vue-router";
import axios from "axios";
import {ElMessage} from "element-plus";

const route = useRoute();

const liveDetail = ref({
  liveId: route.query.id,
  liveTitle: route.query.liveTitle,
  url: route.query.streamKey
});

// 商品数据
const products = ref([]);
// 当前选中的商品
const currentProduct = ref(null);
// 购买弹窗显示状态
const buyDialogVisible = ref(false);
// 加载状态
const loading = ref(false);

// 订单表单
const orderForm = ref({
  userId: null,
  merchantId: 0,
  shippingAddress: '',
  contactPhone: '',
  contactName: '',
  remark: '',
  items: [
    {
      productId: null,
      productName: '',
      productImage: '',
      quantity: 1,
      price: 0
    }
  ],
  freight: 10,
  paymentType: 1
});

// 获取商品图片（处理多图情况）
const getProductImage = (product) => {
  if (!product.imageUrls || product.imageUrls.length === 0) {
    return 'https://via.placeholder.com/80?text=无图片';
  }
  return product.imageUrls[0] || 'https://via.placeholder.com/80?text=无图片';
};

// 格式化价格
const formatPrice = (price) => {
  return price ? parseFloat(price).toFixed(2) : '0.00';
};

// 显示购买弹窗
const showBuyDialog = (product) => {
  currentProduct.value = product;

  // 更新订单表单中的商品信息
  orderForm.value.items[0] = {
    productId: product.id,
    productName: product.name,
    productImage: product.imageUrls[0],
    quantity: 1,
    price: product.price
  };

  buyDialogVisible.value = true;
};

// 关闭购买弹窗
const handleBuyDialogClose = () => {
  // 重置表单（可选）
  orderForm.value = {
    ...orderForm.value,
    shippingAddress: '',
    contactPhone: '',
    contactName: '',
    remark: '',
    items: [{
      ...orderForm.value.items[0],
      quantity: 1
    }]
  };
};

// 刷新商品列表
const refreshProducts = () => {
  loading.value = true;
  axios.get(BASE_URL+'/api/v1/product/liveProduct', {
    params: {
      liveId: liveDetail.value.liveId
    }
  })
      .then((response)=>{
        if (response.data.code == 2000) {
          products.value = response.data.data.map(item => ({
            ...item,
            // 确保图片URL是数组格式
            imageUrls: item.imageUrls ? item.imageUrls.split(',') : []
          }));
        } else {
          ElMessage.error(response.data.msg);
        }
      })
      .catch(error => {
        console.error('获取商品列表失败:', error);
        ElMessage.error('获取商品列表失败，请稍后重试');
      })
      .finally(() => {
        loading.value = false;
      });
};

// 确认购买
const confirmBuy = async () => {
  try {
    // 验证必填字段
    if (!orderForm.value.shippingAddress) {
      ElMessage.warning('请输入收货地址');
      return;
    }
    if (!orderForm.value.contactPhone) {
      ElMessage.warning('请输入联系电话');
      return;
    }
    if (!orderForm.value.contactName) {
      ElMessage.warning('请输入收货人姓名');
      return;
    }

    // 检查库存是否足够
    if (orderForm.value.items[0].quantity > currentProduct.value.stock) {
      ElMessage.warning('库存不足');
      return;
    }

    // 设置用户ID和商家ID
    // 注意：这里需要根据实际用户登录状态获取用户ID
    orderForm.value.userId = getUser().id;
    orderForm.value.merchantId = currentProduct.value.merchantId;

    const response = await axios.post(BASE_URL+'/api/v1/order/private/createLive', orderForm.value);

    if (response.data.code == 2000) {
      ElMessage.success('订单创建成功');
      buyDialogVisible.value = false;
      // 跳转到订单支付页面
      // router.push(`/order/pay?id=${response.data.data.orderId}`);
    } else {
      ElMessage.error(response.data.msg || '订单创建失败');
    }
  } catch (error) {
    console.error('订单创建失败:', error);
    ElMessage.error('订单创建失败: ' + (error.response?.data?.msg || error.message));
  }
};

// 初始化视频播放器
const videoplayer = ref(null);
const myPlayer = ref(null);

onMounted(() => {
  // 初始化播放器
  myPlayer.value = videojs(videoplayer.value, {
    autoplay: true,
    controls: true,
    controlBar: true,
    bigPlayButton: true,
    sources: [{
      src: liveDetail.value.url,
      type: 'application/x-mpegURL'
    }]
  }, () => {
    console.log('播放器加载完成');
  });

  // 初始加载商品
  refreshProducts();
});
</script>

<style scoped>
.live-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Arial', sans-serif;
  background-color: #ffffff;
}

.live-content {
  display: flex;
  gap: 20px;
}

/* 左侧直播播放器样式 */
.live-player-container {
  flex: 3;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.live-header {
  padding: 15px 20px;
  background-color: #fff;
  border-bottom: 1px solid #eaeaea;
}

.live-header h1 {
  margin: 0;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

.live-id {
  margin: 5px 0 0;
  color: #666;
  font-size: 14px;
}

.video-wrapper {
  position: relative;
  padding-top: 56.25%; /* 16:9 比例 */
  height: 0;
  background-color: rgb(18, 9, 37);
}

.video-wrapper .video-js {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

/* 右侧商品栏样式 */
.products-container {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  max-height: 80vh;
  overflow-y: auto;
}

.products-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eaeaea;
}

.products-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
  font-weight: 600;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.header-actions p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.refresh-btn {
  background-color: #f8f9fa;
  color: #333;
  border: 1px solid #ddd;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.2s;
}

.refresh-btn:hover {
  background-color: #e9ecef;
  border-color: #c6c6c6;
}

.refresh-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23333'%3E%3Cpath d='M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6 0 2.97-2.17 5.43-5 5.91V19h2v-2h4v-2h-4v-2h4v-2h-4V9c1.1 0 2-.9 2-2 0-1.1-.9-2-2-2z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
}

.products-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.product-item {
  display: flex;
  gap: 10px;
  padding: 10px;
  border-radius: 6px;
  background-color: #f9f9f9;
  transition: all 0.2s;
}

.product-item:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px);
}

.product-image {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  background-color: #f5f5f5;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.product-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.product-description {
  margin: 0;
  font-size: 13px;
  color: #666;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.product-price {
  color: #e53935;
  font-weight: bold;
  font-size: 18px;
}

.product-stock {
  font-size: 13px;
  color: #4CAF50;
  background-color: rgba(76, 175, 80, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.product-stock.low-stock {
  color: #FF5722;
  background-color: rgba(255, 87, 34, 0.1);
}

.product-origin {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.add-to-cart {
  background-color: #ff6b6b;
  color: white;
  border: none;
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  margin-top: 10px;
}

.add-to-cart:hover {
  background-color: #ff5252;
}

.cart-icon {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23fff'%3E%3Cpath d='M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
}

.empty-products {
  text-align: center;
  padding: 40px 0;
  color: #999;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  display: inline-block;
  width: 60px;
  height: 60px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='%23ccc'%3E%3Cpath d='M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm-1-13h2v6h-2zm0 8h2v2h-2z'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: center;
  margin-bottom: 15px;
  opacity: 0.6;
}

/* 弹窗样式 */
.dialog-product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-product-details {
  flex: 1;
}

.dialog-product-details h3 {
  margin: 0 0 10px 0;
  font-size: 18px;
  color: #333;
}

.dialog-product-details p {
  margin: 5px 0;
}

.order-summary {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px solid #eee;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
}

.summary-item.total {
  font-weight: bold;
  font-size: 16px;
}

.summary-item .value {
  color: #e53935;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .live-content {
    flex-direction: column;
  }

  .products-container {
    max-height: none;
  }

  .product-item {
    flex-direction: column;
  }

  .product-image {
    width: 100%;
    height: auto;
    aspect-ratio: 1/1;
  }
}
</style>